package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.config.BaseDataInit;
import com.wing.product.model.entity.ProductOrder;
import com.wing.product.model.entity.ProductOrderCabinetDetail;
import com.wing.product.model.entity.ProductOrderCutterDetail;
import com.wing.product.model.request.ProductOrderForm;
import com.wing.product.model.response.ProductOrderCabinetDetailVO;
import com.wing.product.model.response.ProductOrderCutterDetailVO;
import com.wing.product.model.response.ProductOrderVO;
import com.wing.product.service.ProductOrderCabinetDetailService;
import com.wing.product.service.ProductOrderCutterDetailService;
import com.wing.product.service.ProductOrderService;
import com.wing.util.PulsarCommons;
import com.wing.util.PulsarUtils;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.pulsar.client.api.PulsarClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-产品订单管理", tags = "#/product/productOrder")
@RestController("productOrderController")
@RequestMapping("product/admin/productOrder")
@RequiredArgsConstructor
@Slf4j
public class ProductOrderController {

    private final ProductOrderService productOrderService;
    @Autowired
    private ProductOrderCabinetDetailService productOrderCabinetDetailService;
    @Autowired
    private ProductOrderCutterDetailService productOrderCutterDetailService;
    @Value("${pulsar.client.topicUrl}")
    private String topicUrl;

    @ApiOperation(value = "查询所有产品订单", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "sn", value="订单编号", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProductOrderVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String sn
    ){
        Page<ProductOrder> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        Long enterpriseId= JwtUtils.getEnterpriseId();
        // 查询当前企业信息
        if(enterpriseId!=null){
            paramMap.put("companyId", enterpriseId);
        }
        if(StringUtils.isNotBlank(sn)){
            paramMap.put("sn", sn);
        }
        IPage<ProductOrderVO> list = productOrderService.pageList4app(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

//    @ApiOperation(value = "添加产品订单", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProductOrderForm.Add.class) ProductOrderForm productOrderForm) {
        if (productOrderService.add(productOrderForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

//    @ApiOperation(value = "修改产品订单", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProductOrderForm.Update.class) ProductOrderForm productOrderForm) {
        ProductOrder productOrder = productOrderService.getById(productOrderForm.getId());
        if(productOrder == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProductOrder.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productOrderForm, productOrder, copyOptions);
        if (productOrderService.updateById(productOrder)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

//    @ApiOperation(value = "删除产品订单", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productOrderId", value = "产品订单id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long productOrderId) {
        if (productOrderService.removeById(productOrderId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询所有产品订单刀柜明细", notes = "详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productOrderId", value="产品订单ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/productOrderCabinetDetailList")
    public PageResult<ProductOrderCabinetDetailVO> productOrderCabinetDetailList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long productOrderId
    ){
        Page<ProductOrderCabinetDetail> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        if(productOrderId != null){
            paramMap.put("productOrderId", productOrderId);
        }
        IPage<ProductOrderCabinetDetailVO> list = productOrderCabinetDetailService.pageList4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询所有产品订单刀具明细", notes = "详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "productOrderId", value="产品订单ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/productOrderCutterDetailList")
    public PageResult<ProductOrderCutterDetailVO> productOrderCutterDetailList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,Long productOrderId
    ){
        Page<ProductOrderCutterDetail> pg = new Page<>(page, limit);
        Map paramMap = new HashMap();
        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        if(productOrderId != null){
            paramMap.put("productOrderId", productOrderId);
        }
        IPage<ProductOrderCutterDetailVO> list = productOrderCutterDetailService.pageList4app(pg, paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "确认收货", notes = "确认收货")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/confirmReceipt")
    public JsonResult confirmReceipt(@RequestParam("id") Long id) {
        ProductOrder productOrder = productOrderService.getById(id);
        if(productOrder.getStatus().equals(ProductOrder.Status.shipped)){
            productOrder.setStatus(ProductOrder.Status.complete);
            if (productOrderService.updateById(productOrder)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "addOrUpdate");
                jsonObject.put("data", productOrder);
                try {
                    PulsarUtils.send(topicUrl + PulsarCommons.All_PRODUCT_ORDER_TOPIC, jsonObject.toJSONString());
                } catch (PulsarClientException e) {
                    log.info(e.getMessage());
                }
                return JsonResult.success("收货成功");
            }
            return JsonResult.fail("收货失败");
        }else{
            return JsonResult.fail("当前状态不能确认收货");
        }
    }

}
